package com.stud.system.controller.system;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.stud.common.annotation.Log;
import com.stud.common.core.controller.BaseController;
import com.stud.common.core.domain.Result;
import com.stud.common.core.page.TableDataInfo;
import com.stud.common.enums.BusinessType;
import com.stud.common.enums.FileBusinessType;
import com.stud.common.exception.ServiceException;
import com.stud.common.utils.StringUtils;
import com.stud.common.utils.file.FileUtils;
import com.stud.common.utils.oss.OssUtil;
import com.stud.common.utils.poi.ExcelUtil;
import com.stud.system.domain.FileLink;
import com.stud.system.service.FileLinkService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 系统文件关联Controller
 *
 * @author Stud
 * @date 2022-10-08
 */
@Api(tags = "系统文件关联")
@RestController
@RequestMapping("/system/fileLink")
@Slf4j
public class FileLinkController extends BaseController {

    @Autowired
    private FileLinkService fileLinkService;

    @ApiOperation("查询系统文件关联列表")
    @PreAuthorize("@ss.hasPermi('system:link:list')")
    @GetMapping("/list")
    public TableDataInfo<FileLink> list(FileLink fileLink) {
        startPage();
        Wrapper<FileLink> wrapper = new QueryWrapper(fileLink);
        List<FileLink> list = fileLinkService.list(wrapper);
        return getDataTable(list);
    }

    @ApiOperation("导出系统文件关联列表")
    @PreAuthorize("@ss.hasPermi('system:link:export')")
    @Log(title = "系统文件关联", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FileLink fileLink) {
        Wrapper<FileLink> wrapper = new QueryWrapper(fileLink);
        List<FileLink> list = fileLinkService.list(wrapper);
        ExcelUtil<FileLink> util = new ExcelUtil<FileLink>(FileLink.class);
        util.exportExcel(response, list, "系统文件关联数据");
    }

    @ApiOperation("获取系统文件关联详细信息")
    @PreAuthorize("@ss.hasPermi('system:link:query')")
    @GetMapping(value = "/{id}")
    public Result<FileLink> getInfo(@PathVariable("id") Long id) {
        return Result.ok(fileLinkService.getById(id));
    }

    @ApiOperation("新增系统文件关联")
    @PreAuthorize("@ss.hasPermi('system:link:add')")
    @Log(title = "系统文件关联", businessType = BusinessType.INSERT)
    @PostMapping
    public Result<Boolean> add(@Validated @RequestBody FileLink fileLink) {
        return Result.ok(fileLinkService.save(fileLink));
    }

    @ApiOperation("修改系统文件关联")
    @PreAuthorize("@ss.hasPermi('system:link:edit')")
    @Log(title = "系统文件关联", businessType = BusinessType.UPDATE)
    @PutMapping
    public Result<Boolean> edit(@Validated @RequestBody FileLink fileLink) {
        return Result.ok(fileLinkService.update(fileLink));
    }

    @ApiOperation("物理删除系统文件关联")
    @PreAuthorize("@ss.hasPermi('system:link:remove')")
    @Log(title = "系统文件关联", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public Result<Boolean> remove(@PathVariable Long[] ids) {
        List<FileLink> fileLinkList = fileLinkService.listByIds(Arrays.asList(ids));
        if (!CollectionUtils.isEmpty(fileLinkList)) {
            fileLinkList.forEach(fileLink -> OssUtil.deleteObject(fileLink.getFileKey()));
        }
        return Result.ok(fileLinkService.removeByIds(ids));
    }


    @ApiOperation("逻辑删除系统文件关联")
    @PreAuthorize("@ss.hasPermi('system:link:remove')")
    @Log(title = "系统文件关联", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeBatchByIds/{ids}")
    public Result<Boolean> removeBatchByIds(@PathVariable Long[] ids) {
        List<FileLink> fileLinkList = fileLinkService.listByIds(Arrays.asList(ids));
        if (!CollectionUtils.isEmpty(fileLinkList)) {
            for (FileLink fileLink : fileLinkList) {
                OssUtil.deleteObject(fileLink.getFileKey());
                fileLink.setDelFlag("1");
            }
        }
        return Result.ok(fileLinkService.updateBatchById(fileLinkList));
    }

    @ApiOperation("逻辑删除系统文件关联")
    @PreAuthorize("@ss.hasPermi('system:link:remove')")
    @Log(title = "系统文件关联", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeByFileKey")
    public Result<Boolean> removeByFileKey(@RequestParam Long businessId, @RequestParam String fileKey) {
        FileLink fileLink = fileLinkService.getOne(new LambdaQueryWrapper<FileLink>().eq(FileLink::getDelFlag, 0).eq(FileLink::getBusinessId, businessId).eq(FileLink::getFileKey, fileKey));
        fileLink.setDelFlag("1");
        return Result.ok(fileLinkService.updateById(fileLink));
    }

    @ApiOperation("上传并关联业务")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file, @RequestParam FileBusinessType businessType, @RequestParam Long businessId, Date expirationTime) {
        return Result.ok(fileLinkService.upload(file, businessType, businessId, expirationTime));
    }

    @ApiOperation("下载文件")
    @GetMapping("/download")
    public void download(@RequestParam Long id, HttpServletResponse response, HttpServletRequest request) {
        try {
            FileLink link = this.fileLinkService.getById(id);
            if (Objects.isNull(link) || StringUtils.isBlank(link.getFileKey())) {
                throw new ServiceException("查询文件失败");
            }
            FileUtils.ossDownload(link.getFileKey(), link.getFileName(), response, request);
        } catch (IOException e) {
            log.error("文件下载失败");
        }
    }

    @ApiOperation("查询关联文件列表")
    @GetMapping("/linkList")
    public TableDataInfo<FileLink> linkList(@RequestParam("businessType") FileBusinessType businessType, @RequestParam Long businessId, String fileType) {
        LambdaQueryWrapper<FileLink> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(FileLink::getBusinessType, businessType);
        queryWrapper.eq(FileLink::getBusinessId, businessId);
        if (!StringUtils.isBlank(fileType)) {
            queryWrapper.eq(FileLink::getFileType, fileType);
        }
        startPage();
        List<FileLink> list = fileLinkService.list(queryWrapper);
        return getDataTable(list);
    }

}
